//
//  LoginViewController.swift
//  BarCode
//
//  Created by xxcao on 2017/3/29.
//  Copyright © 2017年 MobileArtisan. All rights reserved.
//


import UIKit

class BCLoginViewController: BCFatherViewController {
    
    var logoImg: UIImageView! //logo
    var txtUser: UITextField! //用户名输入框
    var txtPwd: UITextField! //密码输入款
    var formView: UIView! //登陆框视图
    var horizontalLine: UIView! //分隔线
    var confirmButton:UIButton! //登录按钮
    var titleLabel: UILabel! //标题标签
    
    var topConstraint: Constraint? //登录框距顶部距离约束
    var serverS: String!
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //视图背景色
        view.backgroundColor = UIColor(red: 28.0/255, green: 202.0/255, blue: 147.0/255,
                                        alpha: 1)
        
       
        
        
  
        
        //登录框高度
        let formViewHeight = 90
        //登录框背景
        formView = UIView()
        formView.layer.borderWidth = 0.5
        formView.layer.borderColor = UIColor.lightGray.cgColor
        formView.backgroundColor = .white
        formView.layer.cornerRadius = 5
        view.addSubview(formView)
        //最常规的设置模式
        formView.snp.makeConstraints { (make) -> Void in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            //存储top属性
            topConstraint = make.centerY.equalTo(view).constraint
            make.height.equalTo(formViewHeight)
        }
        
        //分隔线
        horizontalLine = UIView()
        horizontalLine.backgroundColor = .lightGray
        formView.addSubview(horizontalLine)
        horizontalLine.snp.makeConstraints { (make) -> Void in
            make.height.equalTo(0.5)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.centerY.equalTo(formView)
        }
        
        //用户名图标
        let imgLock1 =  UIImageView(frame:CGRect(x: 11, y: 11, width: 22, height: 22))
        imgLock1.image = UIImage(named:"iconfont-user")
        
        //密码图标
        let imgLock2 =  UIImageView(frame:CGRect(x: 11, y: 11, width: 22, height: 22))
        imgLock2.image = UIImage(named:"iconfont-password")
        
        //用户名输入框
        txtUser = UITextField()
        txtUser.delegate = self
        txtUser.placeholder = "用户名"
        txtUser.tag = 100
        txtUser.leftView = UIView(frame:CGRect(x: 0, y: 0, width: 44, height: 44))
        txtUser.leftViewMode = .always
        txtUser.returnKeyType = .next
        txtUser.clearButtonMode = .whileEditing
        txtUser.keyboardType = .asciiCapable
        txtUser.autocapitalizationType = .none
        txtUser.textColor = UIColor(hex: "333333")
        //用户名输入框左侧图标
        txtUser.leftView!.addSubview(imgLock1)
        formView.addSubview(txtUser)
        
        //布局
        txtUser.snp.makeConstraints { (make) -> Void in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(44)
            make.centerY.equalTo(formView).offset(-formViewHeight/4)
        }
        
        //密码输入框
        txtPwd = UITextField()
        txtPwd.delegate = self
        txtPwd.placeholder = "密码"
        txtPwd.isSecureTextEntry = true
        txtPwd.tag = 101
        txtPwd.leftView = UIView(frame:CGRect(x: 0, y: 0, width: 44, height: 44))
        txtPwd.leftViewMode = .always
        txtPwd.returnKeyType = .next
        txtPwd.clearButtonMode = .whileEditing
        txtPwd.textColor = UIColor(hex: "333333")

        //密码输入框左侧图标
        txtPwd.leftView!.addSubview(imgLock2)
        formView.addSubview(txtPwd)
        
        //布局
        txtPwd.snp.makeConstraints { (make) -> Void in
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(44)
            make.centerY.equalTo(formView).offset(formViewHeight/4)
        }
        
        //登录按钮
        confirmButton = UIButton()
        confirmButton.setTitle("登  录", for: UIControlState())
        confirmButton.setTitleColor(UIColor(hex:"333333"),
                                         for: UIControlState())
        confirmButton.layer.cornerRadius = 5
        confirmButton.backgroundColor = UIColor(colorLiteralRed: 1, green: 1, blue: 1,
                                                     alpha: 0.5)
        confirmButton.addTarget(self, action: #selector(loginConfrim),
                                     for: .touchUpInside)
        view.addSubview(confirmButton)
        confirmButton.snp.makeConstraints { (make) -> Void in
            make.left.equalTo(15)
            make.top.equalTo(formView.snp.bottom).offset(20)
            make.right.equalTo(-15)
            make.height.equalTo(44)
        }
        
        //标题label
        titleLabel = UILabel()
        titleLabel.text = "mobartisan.com"
        titleLabel.textColor = .white
//        titleLabel.backgroundColor = .red
        titleLabel.font = UIFont.systemFont(ofSize: 36)
        view.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { (make) -> Void in
            make.bottom.equalTo(formView.snp.top).offset(-15)
            make.centerX.equalTo(view)
            make.height.equalTo(40)
        }
        //增加背景手势
        let tap = UITapGestureRecognizer(target: self, action: #selector(tapGR))
        view.addGestureRecognizer(tap)
        
        
        //logo
        logoImg = UIImageView()
        logoImg.image = UIImage(named: "timg");
        logoImg.layer.cornerRadius = 30.0
        logoImg.layer.masksToBounds = true
        view.addSubview(logoImg)
        logoImg.snp.makeConstraints { (make) in
            make.bottom.equalTo(titleLabel.snp.top).offset(-20)
            make.centerX.equalTo(view)
            make.width.height.equalTo(self.logoWidth())
        }
        
        
        //服务器设置
        _ = UIButton().then {
            $0.setImage(UIImage(named: "serverIcon"), for: .normal)
            $0.addTarget(self, action: #selector(jumpToServerSetting(sender:)), for: .touchUpInside)
            view.addSubview($0)
            $0.snp.makeConstraints({ make in
                make.right.equalToSuperview().offset(-15)
                make.bottom.equalToSuperview().offset(-8)
            })
            $0.showsTouchWhenHighlighted = true
            $0.isHidden = true
        }
        
        
        //版本号
        _ = UILabel().then {
            $0.textColor = .white
            $0.font = UIFont.systemFont(ofSize: 14)
            view.addSubview($0)
            $0.snp.makeConstraints({ make in
                make.left.equalToSuperview().offset(15)
                make.bottom.equalToSuperview().offset(-8)
            })
            $0.text = Constants().app_version as! String?
        }
 
        //just for test
        var userName = UserDefaults.standard.string(forKey: UserDefaultsKey.userName.rawValue)
        if userName != nil && userName?.characters.count != 0 {
            txtUser.text = userName
        }
        
        var userPsd = UserDefaults.standard.string(forKey: UserDefaultsKey.userPsd.rawValue)
        if userPsd != nil && userPsd?.characters.count != 0 {
            txtPwd.text = userPsd
        }
    }
    
    func tapGR() {
        view.endEditing(true)
        //视图约束恢复初始设置
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.configLogoFrame(isBig: true)
            self.topConstraint?.update(offset: 0)
            self.view.layoutIfNeeded()
        })
    }
    @objc private func jumpToServerSetting(sender: Any){
        let serverSettingVC = BCServerSettingViewController()
        let nav = BCNavigationController(rootViewController: serverSettingVC)
        present(nav, animated: true, completion: nil)
    }
    
    //登录按钮点击
    func loginConfrim(){
        
//        if isHasBigVersion {
//            let appDelegate = AppDelegate()
//            appDelegate.checkApp(serVersion: serverVersion)
//            return
//        }
        self.configLogoFrame(isBig: true)
        guard checkUserNameAndPsd() else {
            SVProgressHUD.dismiss(withDelay: 2)
            return;
        }
        SVProgressHUD.show()
        //收起键盘
        view.endEditing(true)
        //视图约束恢复初始设置
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.topConstraint?.update(offset: 0)
            self.view.layoutIfNeeded()
        })
        
        BmobManager.login(userName: txtUser.text!, psdword: txtPwd.text!) { [unowned self] (result, status) -> (Void) in
            if(status == .NRSSuccess) {
                let dic = result as! Dictionary<String, Any>
                    SVProgressHUD.showSuccess(withStatus: "登录成功")
                    //同步人员
                    BmobManager.getUsers(result: { (users, status) -> (Void) in
                        
                    })
                    SVProgressHUD.dismiss(withDelay: 1.0) {
                        //保存数据
                        UserDefaults.standard.set(self.txtUser.text, forKey: UserDefaultsKey.userName.rawValue)
                        UserDefaults.standard.set(self.txtPwd.text, forKey: UserDefaultsKey.userPsd.rawValue)
                        print("dic:\(dic)")
                        //存 user
                        gUser.transeferDic2User(dic: dic)
                        
                        let rootVC = BGRootViewController();
                        let window = self.view.window
                        window?.rootViewController = rootVC
                        window?.makeKeyAndVisible()
                    }
                
            } else {
                SVProgressHUD.showError(withStatus: result as! String)
            }
        }
    }
    //MARK: - check func
    func checkUserNameAndPsd() -> Bool{
        //用户名5-20
        if txtUser.text == nil || txtUser.text?.characters.count == 0 {
            SVProgressHUD.showError(withStatus: "用户名不能为空")
            return false
        }
        if((txtUser.text?.characters.count)! < 5) {
            SVProgressHUD.showError(withStatus: "用户名不能小于5个字符")
            return false
        }
        if ((txtUser.text?.characters.count)! > 20) {
            SVProgressHUD.showError(withStatus: "用户名不能大于20个字符")
            return false
        }
        //密码5-10
        if txtPwd.text == nil || txtPwd.text?.characters.count == 0 {
            SVProgressHUD.showError(withStatus: "密码不能为空")
            return false
        }
        if ((txtPwd.text?.characters.count)! < 5) {
            SVProgressHUD.showError(withStatus: "密码不能小于5个字符")
            return false
        }
        if ((txtPwd.text?.characters.count)! > 10) {
            SVProgressHUD.showError(withStatus: "密码不能大于10个字符")
            return false
        }
        return true;
    }
    
    //MARK: - logo Frame
    func configLogoFrame(isBig: Bool) -> () {
        print(self.titleLabel.frame.origin.y);
        let logoWidth = self.logoWidth()
        
        guard isBig else {//缩小
            logoImg.snp.updateConstraints { (make) in
                make.width.equalTo(60)
                make.height.equalTo(60)
            }
            return
        }
        //放大
        logoImg.snp.updateConstraints { (make) in
            make.width.height.equalTo(logoWidth)
        }
    }
    
    //屏幕尺寸
    func logoWidth() -> CGFloat {
        let height = UIScreen.main.bounds.size.height
        switch height {
        case 480:
            return 100
        case 568:
            return 120
        case 667:
            return 150
        case 736:
            return 180
        default:
            return 120
        }
    }
    //版本比较
//    func comparVersion() -> Bool {
//        let alert = CustomAlertView()
//        let isShow: Bool =  alert.checkAppServerSion(self.serverS, isClickApp: false)
//        if isShow {
//            return true
//        }
//        return false
//    }
    
}

extension BCLoginViewController: UITextFieldDelegate {
    //输入框获取焦点开始编辑
    func textFieldDidBeginEditing(_ textField:UITextField)
    {
        
        UIView.animate(withDuration: 0.3, animations: { () -> Void in
            self.configLogoFrame(isBig: false)
            self.topConstraint?.update(offset: -100)
            self.view.layoutIfNeeded()
        })
    }
    
    //输入框返回时操作
    func textFieldShouldReturn(_ textField:UITextField) -> Bool
    {
        let tag = textField.tag
        switch tag {
        case 100:
            txtPwd.becomeFirstResponder()
        case 101:
            loginConfrim()
        default:
            print(textField.text!)
        }
        return true
    }

}
